#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
	RenderWindow app(sf::VideoMode(256 + 2 * 64, 256 + 2 * 64), "15-Puzzle! --YzhCat");
	app.setFramerateLimit(60);
	Texture t;
	t.loadFromFile("../images/15.png");

	int w = 64;
	int grid[6][6] = {0};
	Sprite sp[20];
	int n = 0;
	for (int i = 0; i < 4; i++)
		for (int j = 0; j < 4; j++)
		{
			n++; // 1~16
			sp[n].setTexture(t);
			sp[n].setTextureRect(IntRect(i * w, j * w, w, w));
			grid[i + 1][j + 1] = n; // 记录1~16
		}
	while (app.isOpen())
	{
		Event e;
		while (app.pollEvent(e))
		{
			if (e.type == Event::Closed)
				app.close();
			if (e.type == Event::KeyPressed)
				if (e.key.code == Keyboard::Escape)
					app.close();
			if (e.type == Event::MouseButtonPressed)
				if (e.mouseButton.button == Mouse::Left)
				{
					Vector2i pos = Mouse::getPosition(app);
					int x = (pos.x - w) / w + 1;
					int y = (pos.y - w) / w + 1;

					int dx = 0;
					int dy = 0;

					// 16为白板
					if (grid[x + 1][y] == 16)
					{
						dx = 1;
						dy = 0;
					}
					if (grid[x][y + 1] == 16)
					{
						dx = 0;
						dy = 1;
					}
					if (grid[x - 1][y] == 16)
					{
						dx = -1;
						dy = 0;
					}
					if (grid[x][y - 1] == 16)
					{
						dx = 0;
						dy = -1;
					}

					int n = grid[x][y];
					grid[x][y] = 16;
					grid[x + dx][y + dy] = n;

					// 动画
					sp[16].move(-dx * w, -dy * w);
					float speed = 7;
					for (int i = 0; i < w; i += speed)
					{
						sp[n].move(speed * dx, speed * dy);
						app.draw(sp[16]);
						app.draw(sp[n]);
						app.display();
					}
				}
		}

		app.clear(Color::White);
		for (int i = 0; i < 4; i++)
			for (int j = 0; j < 4; j++)
			{
				int n = grid[i + 1][j + 1];
				sp[n].setPosition(i * w + w, j * w + w);
				app.draw(sp[n]);
			}
		app.display();
	}

	return 0;
}
